package mil.af.amc.adpetracker.web.actions.EquipmentItem.ajax;

import mil.af.amc.adpetracker.model.EquipmentItem;
import mil.af.amc.adpetracker.service.EquipmentItemService;
import mil.af.amc.adpetracker.web.actions.AbstractAction;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Please Fill in this Javadoc
 *
 * @author TSgt Jason Ferguson
 */

public class GetEquipmentItemDescriptionAction extends AbstractAction {

    private static final Log log = LogFactory.getLog(GetEquipmentItemDescriptionAction.class);

    private EquipmentItemService equipmentItemService;

    public void setEquipmentItemService(EquipmentItemService equipmentItemService) {
        this.equipmentItemService = equipmentItemService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws Exception {

        int itemModelId = Integer.parseInt(httpServletRequest.getParameter("itemModelId"));
        List<EquipmentItem> results = equipmentItemService.getAllByItemModel(itemModelId);
        EquipmentItem item = results.get(results.size() - 1);  // get the LAST value, not the first one... more likely to be the one the user wants

        //int itemId = Integer.parseInt(httpServletRequest.getParameter("itemId"));
        //EquipmentItem item = equipmentItemService.getById(itemId);

        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("description", item.getDescription());
        resultMap.put("cost", item.getOriginalCost());

        String dateFormatPattern = "dd-MMM-yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormatPattern);
        if (item.getPurchaseDate() != null) {
        String strDate = sdf.format(item.getPurchaseDate());
        resultMap.put("purchaseDate", strDate);
        } else {
            resultMap.put("purchaseDate", "");
        }


        JSONObject jsonObject = JSONObject.fromObject(resultMap);

        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(jsonObject);

        return null;
    }
}
